﻿using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WeatherHistory.Data.Repositories.Interfaces;

namespace WeatherHistory.Api.CommandsQueries.Queries.Accounts.Search;

public class SearchAccountsQueryHandler : IRequestHandler<SearchAccountsQueryRequest, SearchAccountsQueryResponse>
{
    private readonly IAccountRepository _accountRepository;
    private readonly IMapper _mapper;

    public SearchAccountsQueryHandler(IMapper mapper, IAccountRepository accountRepository)
    {
        _mapper = mapper;
        _accountRepository = accountRepository;
    }

    public async Task<SearchAccountsQueryResponse> Handle(SearchAccountsQueryRequest request, CancellationToken cancellationToken)
    {
        var response = new SearchAccountsQueryResponse();
        var accountsQuery = _accountRepository.AsQueryable();

        if (request.FirstName != null) accountsQuery = accountsQuery.Where(x => x.FirstName.ToLower().Contains(request.FirstName.ToLower()));
        if (request.LastName != null) accountsQuery = accountsQuery.Where(x => x.LastName.ToLower().Contains(request.LastName.ToLower()));
        if (request.Email != null) accountsQuery = accountsQuery.Where(x => x.Email.ToLower().Contains(request.Email.ToLower()));

        response.Items = await accountsQuery
            .ProjectTo<SearchAccountsQueryAccountDto>(_mapper.ConfigurationProvider)
            .OrderBy(x => x.Id)
            .Skip(request.From)
            .Take(request.Size)
            .ToListAsync(cancellationToken);

        return response;
    }
}